import { LogicFlow } from "@logicflow/core";
import { Control, MiniMap, SelectionSelect } from "@logicflow/extension";

import UserTask from "./tool/userTaskView.js";
import "@logicflow/core/dist/style/index.css";
import "@logicflow/extension/lib/style/index.css";
export default {
  title:"logicFlow案例",
  components: {},
  data() {
    return {
      graph: null,
      context: null,
      lf: null,
    };
  },
  computed: {},
  watch: {},
  mounted() {
    // 创建容器
    const lf = new LogicFlow({
      container: document.querySelector("#container"),
      plugins: [Control, MiniMap, SelectionSelect],
      grid: {
        size: 20,
        visible: true,
        type: "mesh",
        config: {
          color: "#bbc4d0",
          thickness: 1,
        },
      },
      // 开启内置快捷键
      keyboard: {
        enabled: true,
      },
    });

    // 批量注册自定义节点
    lf.batchRegister([
      {
        type: "StartNode",
        view: UserTask.view,
        model: UserTask.model,
      },
      {
        type: "DataNode",
        view: UserTask.view,
        model: UserTask.model,
      },
      {
        type: "EndNode",
        view: UserTask.view,
        model: UserTask.model,
      },
    ]);

    // 为菜单追加选项（必须在 lf.render() 之前设置）
    // lf.extension.menu.addMenuConfig({
    //   nodeMenu: [
    //     {
    //       text: "属性",
    //       callback(node) {
    //         console.log(`
    //       节点id：${node.id}
    //       节点类型：${node.type}
    //       节点坐标：(x: ${node.x}, y: ${node.y})`);
    //       },
    //     },
    //   ],
    //   edgeMenu: [
    //     {
    //       text: "属性",
    //       callback(edge) {
    //         console.log(`
    //       连线id：${edge.id}
    //       连线类型：${edge.type}
    //       连线坐标：(x: ${edge.x}, y: ${edge.y})
    //       源节点id：${edge.sourceNodeId}
    //       目标节点id：${edge.targetNodeId}`);
    //       },
    //     },
    //   ],
    // });

    // 添加导航栏(覆写原本的区域适应方法;新增小地图)
    lf.extension.control.removeItem("reset");
    lf.extension.control.addItem({
      iconClass: "lf-control-fit",
      text: "区域适应",
      title: "区域自适应",
      key: "reset",
      onClick: (lf, ev) => {
        lf.fitView(100, 100);
      },
    });
    lf.extension.control.addItem({
      iconClass: "custom-minimap",
      text: "地图导航",
      title: "展示小地图",
      key: "minimap",
      onClick: (lf, ev) => {
        const position = lf.getPointByClient(ev.x, ev.y);
        lf.extension.miniMap.show(
          position.domOverlayPosition.x - 120,
          position.domOverlayPosition.y + 35
        );
      },
    });

    // 设置主题
    lf.setTheme({
      baseNode: {
        fill: "#FFFFFF",
        stroke: "green",
        strokeWidth: 2,
      },
      // 箭头记号
      arrow: {
        offset: 4,
        verticalLength: 3,
      },
      // 连线样式
      polyline: {
        fill: "none",
        stroke: "rgb(135, 144, 160)",
        strokeWidth: 1,
        strokeDasharray: "3, 2",
      },
    });

    // 初始化节点
    lf.render({
      nodes: [
        {
          id: "1",
          type: "StartNode",
          x: 100,
          y: 300,
          properties:{
            title: '开始节点'
          }
        },
      ],
      edges: [],
    });

    // 添加点击事件
    lf.on("node:click", (args) => {
      console.log("node:args", args);
      console.log("node:data", args.data);
      console.log("node:id", args.data.id);
      console.log("node:position", args.position);

      // 获取自定义属性
      console.log("node:getProperties", lf.getProperties(args.data.id));
      // 设置自定义属性
      // lf.setProperties(args.data.id, { content: "zhangsan" });
      // 将图形选中
      // lf.selectElementById(args.data.id);
      // 删除元素
      // lf.deleteElement(args.data.id);
      // 获取节点model
      // console.log(lf.getNodeDataById(args.data.id));
      // 删除节点属性
      // lf.deleteProperty(args.data.id, 'content');
      // 清空画布
      // lf.clearData();
    });

    lf.on("node:mouseenter", (args) => {
      // 修改状态 不可删除,否则无法监听到鼠标移入事件
      lf.getNodeModelById(args.data.id).setProperties({ isSelect: true });
    });

    lf.on("node:mouseleave", (args) => {
      // 修改状态 不可删除,否则无法监听到鼠标移入事件
      lf.getNodeModelById(args.data.id).setProperties({ isSelect: false });
    });

    lf.on("node:add-node", (args) => {
      const { graphModel, model, type, title } = args;
      const pos = this.genNewNodePos(lf, model);
      let newNode = {
        id: 'node' + Number(Math.random().toString().substr(2,10) + Date.now()).toString(36),
        type: type,
        properties: {
          title: title
        },
        x: pos.x,
        y: pos.y,
      };

      let newNodeModel = graphModel.addNode(newNode);
      let newGraph = {
        id: 'line' + Number(Math.random().toString().substr(2,10) + Date.now()).toString(36),
        type: "polyline",
        sourceNodeId: model.id,
        targetNodeId: newNodeModel.id,
      };
      graphModel.addEdge(newGraph);
    });

    this.lf = lf;
  },
  methods: {
    getGraphData() {
      console.log(this.lf.getGraphData());
      console.log(this.lf);
      const { model, graphModel } = this.lf;
    },

    getGraphRawData() {
      console.log(this.lf.getGraphRawData());
    },

    setGraphRawData() {
      let data = {
        nodes: [
          {
            id: "1",
            type: "UserTask",
            x: 100,
            y: 300,
            properties: {
              name: "张三",
            },
          },
          {
            id: "2",
            type: "rect",
            x: 300,
            y: 300,
            text: "节点2",
          },
          {
            id: "3",
            type: "rect",
            x: 500,
            y: 300,
            text: "节点1",
          },
          {
            id: "4",
            type: "rect",
            x: 700,
            y: 300,
            text: "节点2",
          },
          {
            id: "5",
            type: "rect",
            x: 1300,
            y: 300,
            text: "节点1",
          },
          {
            id: "6",
            type: "rect",
            x: 900,
            y: 300,
            text: "节点2",
          },
          {
            id: "7",
            type: "rect",
            x: 1100,
            y: 300,
            text: "节点1",
          },
        ],
        edges: [
          {
            sourceNodeId: "1",
            targetNodeId: "2",
            type: "polyline",
          },
        ],
      };
      // this.lf.render(data);
      this.lf.graphModel.graphDataToModel(data);
    },

    /**
     * 基于当前节点生成一个节点的位置
     */
    genNewNodePos(lf, nodeModel) {
      const outgoingNodes = lf.getNodeOutgoingNode(nodeModel.id);
      console.log(outgoingNodes);
      if (outgoingNodes.length) {
        const bound = this.getNodesRect(outgoingNodes);
        const x = bound.minX;
        const y = bound.maxY + 80;
        return {
          x,
          y,
        };
      } else {
        return {
          x: nodeModel.x + 180,
          y: nodeModel.y,
        };
      }
    },

    /**
     * 获取当前所有节点的边界
     */
    getNodesRect(nodes) {
      const maxX = nodes.reduce((val, node) => {
        return Math.max(val, node.x);
      }, 0);
      const maxY = nodes.reduce((val, node) => {
        return Math.max(val, node.y);
      }, 0);
      const minX = nodes.reduce((val, node) => {
        return Math.min(val, node.x);
      }, Infinity);
      const minY = nodes.reduce((val, node) => {
        return Math.min(val, node.y);
      }, Infinity);
      console.log(minX, minY, maxX, maxY);
      return { minX, minY, maxX, maxY };
    },
  },
};
